package com.javaking.clanteam.studentutils.utils;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class TabsAdapter extends FragmentPagerAdapter 
		implements OnPageChangeListener, TabListener {
	
	List<Fragment> mTabs;
	ActionBar mActionBar;
	ViewPager mPager;

	public TabsAdapter(SherlockFragmentActivity act, ViewPager pager) {
		super(act.getSupportFragmentManager());
		mTabs = new ArrayList<Fragment>();
		mPager = pager;
		mPager.setAdapter(this);
		mPager.setOnPageChangeListener(this);
		mActionBar = act.getSupportActionBar();
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		mActionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
	}
	
	public void addTab(Fragment tab, int location) {
		if (location!=-1) {
			location=mTabs.size();
		}
		
		mTabs.add(location,tab);
		Tab newTab = mActionBar.newTab();
		newTab.setTabListener(this);
		newTab.setTag(tab);
		notifyDataSetChanged();
	}
	
	public void addTab(Fragment tab) {
		addTab(tab,-1);
	}

	@Override
	public Fragment getItem(int index) {
		return mTabs.get(index);
	}

	@Override
	public int getCount() {
		return mTabs.size();
	}

	public void addTabs(List<Fragment> tabs) {
		for (Fragment tab : tabs) {
			addTab(tab);
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {}

	@Override
	public void onPageSelected(int position) {
		mActionBar.setSelectedNavigationItem(position);
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		Object tag = tab.getTag();
		for (int i = 0; i<mTabs.size(); i++) {
			if (mTabs.get(i) == tag) {
				mPager.setCurrentItem(i);
			}
		}
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {}
}
